package cn.laixueit.controller;

import cn.laixueit.commons.Utils;
import cn.laixueit.mapper.StudentMapper;
import cn.laixueit.pojo.Classes;
import cn.laixueit.pojo.Student;
import cn.laixueit.pojo.Teacher;
import cn.laixueit.service.ClassesService;
import cn.laixueit.service.StudentService;
import cn.laixueit.service.impl.FileService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.sound.midi.Soundbank;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private FileService fileService;

    @GetMapping("/add")
    public String add(Model model){
        List<Classes> classList =  studentService.findClassList();
        model.addAttribute("classList",classList);
        return "studentAdd";
    }


    @PostMapping("/save")
    public String save(Student student){
        studentService.save(student);
        return "redirect:page";
    }

    @GetMapping("/page")
    public String page(@RequestParam(defaultValue = "1")Integer start,
                       @RequestParam(defaultValue = "10")Integer size,
                       @ModelAttribute Student student,
                       Model model){
        PageInfo<Student> pageInfo =  studentService.page(start,size,student);
        model.addAttribute("pageInfo",pageInfo);
        List<Classes> classList = studentService.findClassList();
        model.addAttribute("classList",classList);
        return "studentList";
    }

    @GetMapping("/findById")
    public String findById(Integer id,Model model){
        Student student = studentService.findById(id);
        model.addAttribute("student",student);
        List<Classes> classList = studentService.findAllClassList();
        model.addAttribute("classList",classList);
        return "studentEdit";
    }

    @PostMapping("/update")
    public String update(Student student, @RequestParam("file")MultipartFile file,HttpServletRequest request){
        String newFileName = fileService.upLoadImg(file, request);
        if(!StringUtils.isEmpty(newFileName)){
            student.setImg(newFileName);
        }
        studentService.update(student);
        return "redirect:page";
    }

    @GetMapping("/removeById")
    @ResponseBody
    public Boolean removeById(Integer id){
        Boolean flag = studentService.removeById(id);
        return flag;
    }
}
